﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using TestSystem.BLL;
using TestSystem.BLL.Helpers;
using TestSystem.BLL.TestSystem;


public partial class QuizDetails : System.Web.UI.Page
{
    private int quizID = -1;
    public int QuizID
    {
        get
        {
            if (quizID == -1)
                quizID = int.Parse(Request.QueryString["quizID"]);
            return quizID;
        }
    }

    private Quiz currentQuiz = null;
    public Quiz CurrentQuiz
    {
        get
        {
            if (currentQuiz == null)
                currentQuiz = Quiz.GetByQuizID(QuizID);
            return currentQuiz;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            lblTitle.Text = CurrentQuiz.Title;
            lblDesc.Text = CurrentQuiz.Description;
            quizInfo.CurrentQuiz = CurrentQuiz;
            btnStart.Text = "Start test";
        }
    }

    protected void btnStart_Click(object sender, EventArgs e)
    {
        if (Session["DataSaved"] != null && Session["TimeLeft"] != null)
        {
            var currentQuiz = Session["CurrentQuiz"] as Quiz;
            if(currentQuiz != null)
            {
                lnkFinishQuiz.NavigateUrl = String.Format(lnkFinishQuiz.NavigateUrl, currentQuiz.QuizID);
                lnkFinishQuiz.Text = currentQuiz.Title;
            }
            errorPanel.Visible = true;
        }
        else
        {
            var curHistory = new QuizHistory();
            curHistory.DateTimeStart = DateTime.Now;
            curHistory.QuizID = QuizID;
            curHistory.UserID = Utils.CurrentUserName;
            var tests = Test.GetByQuizID(QuizID);
            Session["Tests"] = TestSystemHelper.GetVariant(Test.GetByQuizID(QuizID), CurrentQuiz);
            if (Session["Tests"] != null)
            {
                Session["CurrentQuiz"] = CurrentQuiz;
                Session["CurrentTest"] = ((List<Test>) Session["Tests"])[0];
                Session["UserAnswers"] = new Dictionary<int, List<UserAnswer>>();
                Session["DataSaved"] = false;
                Session["QuizHistory"] = curHistory;
                Response.Redirect("QuizRunner.aspx");
            }
        }
    }
}
